//
//  WJFileSharingManager.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/28.
//

import UIKit

class WJFileSharingManager {
    
    static let shared = WJFileSharingManager()
    private var activeTempFiles: [URL] = []
    private let fileManager = FileManager.default
    
    func shareFile(at fileURL: URL,
                  withFileName customFileName: String,
                  from viewController: UIViewController) {
        WJProgressHUD.showLoading()
        
        DispatchQueue.global(qos: .userInitiated).async {
            // 创建临时文件
            let tempFileURL = self.createTemporaryFile(from: fileURL, with: customFileName)
            
            DispatchQueue.main.async {
                WJProgressHUD.dismiss()
                
                let fileItemSource = WJFileActivityItemSource(
                    originalFileURL: fileURL,
                    customFileName: customFileName
                ) { [weak self] in
                    self?.cleanupTempFile(tempFileURL)
                }
                
                let activityVC = UIActivityViewController(
                    activityItems: [fileItemSource],
                    applicationActivities: nil
                )
                
                // 设置分享完成回调
                activityVC.completionWithItemsHandler = { [weak self] activityType, completed, returnedItems, error in
                    print("分享完成: \(completed), 活动类型: \(activityType?.rawValue ?? "nil")")
                    
                    // 延迟清理临时文件，确保分享操作完全结束
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                        fileItemSource.cleanup()
                        self?.cleanupTempFile(tempFileURL)
                    }
                }
                
                // 配置 iPad 弹出位置
                if let popoverController = activityVC.popoverPresentationController {
                    popoverController.sourceView = viewController.view
                    popoverController.sourceRect = CGRect(
                        x: viewController.view.bounds.midX,
                        y: viewController.view.bounds.midY,
                        width: 0, height: 0
                    )
                }
                
                viewController.present(activityVC, animated: true)
            }
        }
    }
    
    private func createTemporaryFile(from originalURL: URL, with fileName: String) -> URL {
        let fileExtension = originalURL.pathExtension
        let tempDirectory = FileManager.default.temporaryDirectory
        let tempFileURL = tempDirectory
            .appendingPathComponent("\(UUID().uuidString)_\(fileName)")
            .appendingPathExtension(fileExtension)
        
        do {
            if fileManager.fileExists(atPath: tempFileURL.path) {
                try fileManager.removeItem(at: tempFileURL)
            }
            try fileManager.copyItem(at: originalURL, to: tempFileURL)
            activeTempFiles.append(tempFileURL)
            print("创建临时文件: \(tempFileURL.lastPathComponent)")
        } catch {
            print("创建临时文件失败: \(error)")
        }
        
        return tempFileURL
    }
    
    private func cleanupTempFile(_ fileURL: URL) {
        if fileManager.fileExists(atPath: fileURL.path) {
            do {
                try fileManager.removeItem(at: fileURL)
                activeTempFiles.removeAll { $0 == fileURL }
                print("成功删除临时文件: \(fileURL.lastPathComponent)")
            } catch {
                print("删除临时文件失败: \(error) - \(fileURL.lastPathComponent)")
            }
        }
    }
    
    // 应用进入后台时清理所有临时文件
    func cleanupAllTempFiles() {
        for tempFile in activeTempFiles {
            cleanupTempFile(tempFile)
        }
        activeTempFiles.removeAll()
    }
    
    // 定期清理旧的临时文件（可选）
    func cleanupOldTempFiles() {
        let tempDirectory = FileManager.default.temporaryDirectory
        do {
            let tempFiles = try fileManager.contentsOfDirectory(at: tempDirectory, includingPropertiesForKeys: [.creationDateKey])
            let oneHourAgo = Date().addingTimeInterval(-3600)
            
            for fileURL in tempFiles {
                if let attributes = try? fileManager.attributesOfItem(atPath: fileURL.path),
                   let creationDate = attributes[.creationDate] as? Date,
                   creationDate < oneHourAgo {
                    cleanupTempFile(fileURL)
                }
            }
        } catch {
            print("清理旧文件失败: \(error)")
        }
    }
}
